#include "timeutil.h"

#include <QDateTime>
#include <QDate>
#include <QTime>


namespace Common {

QString TimeUtil::getTimeStamp(QString format)
{
    QDateTime dtime = QDateTime::currentDateTime();
    return dtime.toString(format);
}

QString TimeUtil::getDate(QString format)
{
    QDate date = QDate::currentDate();
    return date.toString(format);
}

QString TimeUtil::getTime(QString format)
{
    QTime time = QTime::currentTime();
    return time.toString(format);
}

qint64 TimeUtil::timeStamp()
{
    return QDateTime::currentDateTime().toMSecsSinceEpoch();
}

qint64 TimeUtil::currentMSecsSinceEpoch()
{
    return QDateTime::currentDateTime().currentMSecsSinceEpoch();
}

qint64 TimeUtil::currentSecsSinceEpoch()
{
    QDateTime epochTime(QDate(1970,1,1),QTime(8,0,0));
    return epochTime.secsTo(QDateTime::currentDateTime());
}

QDateTime TimeUtil::addMSecsToEpoch(qint64 mSeonds)
{
    QDateTime epochTime(QDate(1970,1,1),QTime(8,0,0));
    return epochTime.addMSecs(mSeonds);
}

QDateTime TimeUtil::addSecsToEpoch(qint64 seonds)
{
    QDateTime epochTime(QDate(1970,1,1),QTime(8,0,0));
    return epochTime.addSecs(seonds);
}

QString TimeUtil::secondFormatHHMMSS(qint64 second)
{
    int hh = second / (60 * 60);
    int mm = (second- (hh * 60 * 60)) / 60;
    int ss = (second - (hh * 60 * 60)) - mm * 60;

    QString strTime = QString("%1:%2:%3")
            .arg(hh, 2, 10, QLatin1Char('0'))
            .arg(mm, 2, 10, QLatin1Char('0'))
            .arg(ss, 2, 10, QLatin1Char('0'));

    return strTime;
}

QString TimeUtil::millisecondFormatHHMMSS(qint64 ms)
{
    int ss = 1000;//ms
    int mm = ss * 60;
    int hh = mm * 60;
    int dd = hh * 24;

    qint64 day = ms / dd;
    qint64 hour = (ms - day * dd) / hh;
    qint64 minute = (ms - day * dd - hour * hh) / mm;
    qint64 second = (ms - day * dd - hour * hh - minute * mm) / ss;
    qint64 milliSecond = ms - day * dd - hour * hh - minute * mm - second * ss;

    QString strTime = QString("%1:%2:%3")
        .arg(hour + day * 24, 2, 10, QLatin1Char('0'))
        .arg(minute, 2, 10, QLatin1Char('0'))
        .arg(second, 2, 10, QLatin1Char('0'));

    return strTime;
}

}//namespace Common
